package com.sein.foods;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

public class DataManipulator {

	private static final String DATABASE_NAME = "foods.db";
	private static final int DATABASE_VERSION = 1;
	static final String TABLE_NAME = "food";
	private static Context context;
	static SQLiteDatabase db;

	private SQLiteStatement insertStmt;

	private static final String INSERT = "insert into " + TABLE_NAME
			+ " (name, number, skypeId, address) values" + "(?,?,?,?)";

	public DataManipulator(Context context) {
		DataManipulator.context = context;
		OpenHelper openHelper = new OpenHelper(DataManipulator.context);
		DataManipulator.db = openHelper.getWritableDatabase();
		this.insertStmt = DataManipulator.db.compileStatement(INSERT);
	}

	public long insert(String name, String number, String skypeId,
			String address) {
		this.insertStmt.bindString(1, name);
		this.insertStmt.bindString(2, number);
		this.insertStmt.bindString(3, skypeId);
		this.insertStmt.bindString(4, address);
		return this.insertStmt.executeInsert();
	}

	public void deleteAll() {
		db.delete(TABLE_NAME, null, null);
	}

	public List<String[]> selectAll() {
		List<String[]> list = new ArrayList<String[]>();
		Cursor cursor = db.query(TABLE_NAME, new String[] { "id", "name",
				"number", "skypeID", "address" }, null, null, null, null,
				"name asc");
		if (cursor.moveToFirst()) {
			do {
				String[] b1 = new String[] { cursor.getString(0),
						cursor.getString(1), cursor.getString(2),
						cursor.getString(3), cursor.getString(4) };
				list.add(b1);
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return list;
	}

	public void delete(int rowId) {
		db.delete(TABLE_NAME, null, null);
	}

	private class OpenHelper extends SQLiteOpenHelper {
		public OpenHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);

		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE "
					+ TABLE_NAME
					+ " (id INTEGER PRIMARY KEY, name TEXT, number TEXT, skypeId TEXT, address TEXT)");
			System.out.println("Table " + TABLE_NAME + " created");

		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			onCreate(db);
		}
	}
}
